package com.micro.service.impl;

import com.micro.controller.Request.MessageRequest;
import com.micro.entity.Message;
import com.micro.repository.MessageRepository;
import com.micro.service.MessageService;
import com.micro.service.client.UserServiceClient;
import com.micro.service.client.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageRepository messageRepository;
    // 引入用户服务Feign客户端（替代直接操作UserRepository）
    @Autowired
    private UserServiceClient userServiceClient;
    //火车票支付成功消息保存
    public void saveTrainTicketMessage(MessageRequest request) {
        //User user = userRepository.findByUsername(request.getUserName());
        UserDTO user = userServiceClient.getUserByUsername(request.getUserName());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        Message message = new Message();
        message.setUserId(user.getUserId());
        message.setMessageType(request.getMessageType());// 0-火车票, 1-火车餐, 2-酒店
        message.setActionType(request.getActionType());
        message.setContent(request.getContent());
        message.setCreateTime(LocalDateTime.now());

        messageRepository.insert(message);
    }

    public List<Message> getMessagesByUserAndType(String username, int type) {
        try {
            UserDTO user = userServiceClient.getUserByUsername(username);
            // 新增空值判断
            if (user == null) {
                System.err.println("用户不存在: " + username);
                return Collections.emptyList();
            }

            Long userId = user.getUserId();
            System.out.println("查询用户消息: username=" + username + ", userId=" + userId + ", type=" + type);
            return messageRepository.findByUserIdAndMessageTypeOrderByCreateTimeDesc(userId, type);
        } catch (Exception e) {
            System.err.println("查询用户消息失败: " + e.getMessage());
            e.printStackTrace();
            return Collections.emptyList();
        }
    }
    /*public List<Message> getMessagesByUserAndType(String username, int type){
        List <Message> msgs = new ArrayList<>();
        //User user = userRepository.findByUsername(username);
        UserDTO user = userServiceClient.getUserByUsername(username);

        Long tmpUserId = user.getUserId();
        msgs = messageRepository.findByUserIdAndMessageTypeOrderByCreateTimeDesc(tmpUserId,type);
        return msgs;
    }*/
}
